// 政策库 - 新增
import React from 'react';
import { observer, useLocalStore } from 'mobx-react-lite';
import { useLocation, useHistory } from 'react-router';
import { parse } from 'qs';
import { Card, Form, Row, Col, Button, Input, message } from 'antd';
import AjaxSelect from '~/components/AjaxSelect';
import * as addApi from '~/apis/user/addApi';
import { genValidConfig } from './pageConfig';
import 'braft-editor/dist/index.css';
import './index.local.sass';

const cardConfig = {
  size: 'small' as const,
  bordered: false,
};

const FormItem = Form.Item;

const formItemLayout = {
  wrapperCol: { span: 20 },
};

const AddOrEditUser = observer(() => {
  const location = useLocation();
  const history = useHistory();

  const querryParams = parse(location.search, { ignoreQueryPrefix: true });

  const state = useLocalStore(() => ({
    id: querryParams.id || '',
    loading: false,
  }));


  const [form] = Form.useForm();

  // 获取表单数据
  const getFormValus = () => form.validateFields().then((values: any) => {
    const params = {
      id: state.id,
      ...values,
      institution: parseInt(values.institution, 10),
    };
    return params;
  });

  const onSubmit = () => {
    getFormValus().then((params) => {
      const _params = {
        ...params,
      };

      addApi.addUser(_params).then(() => {
        message.success('success');
        history.push('/user/management');
      });
    }).catch(() => {
      message.error('validation error');
    });
  };

  const onSaveAndClose = () => {
    history.push('/user/management');
  };

  // 表单填充
  const fillForm = (formData: any) => {
    const {
      username,
      nickname,
      password,
      phone,
      email,
      institution,
      examineRole,
      reserved,
    } = formData;

    form.setFieldsValue({
      username,
      nickname,
      password,
      phone,
      email,
      institution: institution.toString(),
      examineRole,
      reserved,
    });
  };

  // initForm
  const initForm = (id: string) => {
    addApi.getUser(id).then((res) => {
      fillForm(res.data);
    });
  };

  React.useEffect(() => {
    if (state.id) {
      initForm(state.id);
    }
  }, []);


  return (
    <div>
      <Card {...cardConfig} className="search-card">
        <Form form={form} layout="vertical" className="w-11/12">
          {/* line 1 */}
          <Row>
            <Col span={10}>
              <FormItem
                label="User name"
                rules={genValidConfig({ name: 'User name' })}
                name="username"
                {...formItemLayout}
              >
                {/* autoComplete="new-password" 防止浏览器自动填充用户名密码 */}
                <Input
                  allowClear={true}
                  autoComplete="new-password"
                  placeholder="Please input"
                />
              </FormItem>
            </Col>
          </Row>
          {/* line 2 */}
          <Row>
            <Col span={10}>
              <FormItem
                label="Nick name"
                rules={genValidConfig({ name: 'Nick name' })}
                name="nickname"
                {...formItemLayout}
              >
                <Input
                  allowClear={true}
                  autoComplete="new-password"
                  placeholder="Please input"
                />
              </FormItem>
            </Col>
          </Row>
          {/* line 3 */}
          <Row>
            <Col span={10}>
              <FormItem
                label="Password"
                rules={genValidConfig({ name: 'Password' })}
                name="password"
                {...formItemLayout}
              >
                <Input.Password
                  allowClear={true}
                  autoComplete="new-password"
                  placeholder="Please input"
                />
              </FormItem>
            </Col>
          </Row>
          {/* line 4 */}
          <Row>
            <Col span={10}>
              <FormItem
                label="Phone number"
                name="phone"
                {...formItemLayout}
              >
                <Input
                  allowClear={true}
                  placeholder="Please input"
                />
              </FormItem>
            </Col>
          </Row>
          {/* line 5 */}
          <Row>
            <Col span={10}>
              <FormItem
                label="Email"
                name="email"
                rules={genValidConfig({ type: 'email', message: 'Email' })}
                {...formItemLayout}
              >
                <Input
                  allowClear={true}
                  placeholder="Please input"
                />
              </FormItem>
            </Col>
          </Row>
          {/* line 6 */}
          <Row align="bottom">
            <Col span={10}>
              <FormItem
                label="institution type"
                name="institution"
                rules={genValidConfig({ name: 'institution type' })}
                {...formItemLayout}
              >
                <AjaxSelect
                  placeholder="Please select"
                  type="pppOrgType"
                />
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem
                noStyle
                shouldUpdate={(prevValues, currentValues) => prevValues.institution !== currentValues.institution}
                {...formItemLayout}
              >{
                  ({ getFieldValue }) => (getFieldValue('institution') === '5' ? (
                    <FormItem name="reserved" rules={genValidConfig({ name: 'reserved' })}>
                      <Input
                        allowClear={true}
                        placeholder="Please input" />
                    </FormItem>
                  ) : <></>)
                }

              </FormItem>
            </Col>
          </Row>
          {/* line 7 */}
          <Row>
            <Col span={10}>
              <FormItem
                label="Role"
                name="examineRole"
                rules={genValidConfig({ name: 'Role' })}
                {...formItemLayout}
              >
                <AjaxSelect
                  placeholder="Please select"
                  type="pppRole"
                />
              </FormItem>
            </Col>
          </Row>
        </Form>
      </Card>

      <div>
        <Button
          type="primary"
          className="mr-2"
          onClick={onSubmit}
        >
         Post
        </Button>

        <Button
          className="mr-2"
          onClick={onSaveAndClose}
        >
          Close
        </Button>
      </div>
    </div>
  );
});

export default AddOrEditUser;
